
# rule_manager.py
import importlib
import os
from pathlib import Path
from functools import partial
class RuleManager:
    def __init__(self):
        self.loaded_rules = {}  # 存储已加载的规则 {rule_name: rule_class}
        self.load_log = []      # 日志记录加载情况
        self._load_all_rules()

    def _load_all_rules(self):
        """
        自动扫描模板目录下的所有规则类
        """
        # 获取当前文件所在目录
        current_dir = Path(__file__).parent

        for rule_folder in current_dir.iterdir():
            if not rule_folder.is_dir() or rule_folder.name.startswith("__"):
                continue

            module_name = rule_folder.name
            rule_file_path = rule_folder / f"{module_name.lower()}_rule.py"

            if not rule_file_path.exists():
                self.load_log.append({
                    "module": module_name,
                    "status": "failed",
                    "reason": "找不到规则文件"
                })
                continue

            try:
                module = importlib.import_module(f"template.{module_name}.{module_name.lower()}_rule")
                class_name = f"{module_name}_Rule"
                rule_class = getattr(module, class_name, None)

                if rule_class and issubclass(rule_class, object):  # 可加更严格的 BaseRule 判断
                    self.loaded_rules[module_name] = rule_class
                    self.load_log.append({
                        "module": module_name,
                        "status": "success",
                        "class": class_name
                    })
                else:
                    self.load_log.append({
                        "module": module_name,
                        "status": "failed",
                        "reason": f"找不到类 {class_name}"
                    })

            except Exception as e:
                self.load_log.append({
                    "module": module_name,
                    "status": "failed",
                    "reason": str(e)
                })

    def execute_rule(self, rule_module, rule_class, project_info):
        if rule_module in self.loaded_rules:
            rule_class = self.loaded_rules[rule_module]
            def fetch_merged_info(**kwargs):
                return kwargs

            rule_instance = rule_class({
                            'fetch_func': fetch_merged_info,
                            'project_info': project_info
                        })
            return rule_instance.process()
        else:
            raise ValueError(f"规则模块 {rule_module} 未被加载")
    def get_load_summary(self):
        """
        返回规则加载摘要
        """
        total = len(self.load_log)
        success = sum(1 for log in self.load_log if log["status"] == "success")
        failed = total - success
        return {
            "total": total,
            "success": success,
            "failed": failed,
            "details": self.load_log
        }

    def print_load_summary(self):
        """
        打印规则加载日志到控制台
        """
        summary = self.get_load_summary()
        print("\n[规则装载] 开始加载以下规则模块：")
        for log in self.load_log:
            if log["status"] == "success":
                print(f"  ✅ {log['class']} ({log['module']})")
            else:
                print(f"  ❌ {log['module']} —— {log['reason']}")
        print(f"[规则装载] 完成，共加载 {summary['total']} 个规则（成功 {summary['success']} 个，失败 {summary['failed']} 个）\n")

if __name__ == "__main__":
    # 设置模板目录
    print( )
    # manager = RuleManager()

    # PROJECT_BASE_INFO = {
    #     '施工单位': '浙江交工宏途交通建设有限公司',
    #     '监理单位': '浙江浙中建设工程管理有限公司',
    #     '单位工程': '路基工程',
    #     '分部工程': '涵洞、通道',
    #     '分项工程': '主体结构',
    #     '施工日期': '2024/05/31',
    #     '施工部位': 'K59+639圆管涵',
    #     '工程地点及桩号':'K59+639圆管涵',
    #     '具体部位':'管座及涵管安装',
    #     '基础宽度': 2759,
    #     '基础厚度': 300,
    #     '基础顶高程': 66035,
    #     '断面尺寸宽度（直径）': 275.9,
    #     '断面尺寸高（厚）度': 30,
    #     '基础混凝土强度（砂浆）等级': 'C25',
    #     '基础设计混凝土（砂浆）用量': '15',
    #     '基础实际混凝土（砂浆）用量': '16',
    #     '护壁混凝土强度（砂浆）等级': 'C25',
    #     '护壁设计混凝土（砂浆）用量': '15',
    #     '护壁实际混凝土（砂浆）用量': '16',
    # }

    # # 示例：执行 JS107_Rule
    # rule_module='GL105'
    # result_df = manager.execute_rule(
    #     rule_module="GL105",
    #     rule_class=f"{rule_module}_Rule",
    #     project_info=PROJECT_BASE_INFO,
    # )
    # print(result_df)





